package utils

import (
	"context"
	"fmt"
	"time"
)

// FormatDuration 格式化持续时间
func FormatDuration(d time.Duration) string {
	if d < time.Second {
		return fmt.Sprintf("%dms", d.Milliseconds())
	}
	if d < time.Minute {
		return fmt.Sprintf("%.1fs", d.Seconds())
	}
	if d < time.Hour {
		minutes := int(d.Minutes())
		seconds := int(d.Seconds()) % 60
		return fmt.Sprintf("%dm%ds", minutes, seconds)
	}

	hours := int(d.Hours())
	minutes := int(d.Minutes()) % 60
	return fmt.Sprintf("%dh%dm", hours, minutes)
}

// FormatTime 格式化时间
func FormatTime(t time.Time) string {
	return t.Format("2006-01-02 15:04:05")
}

// FormatTimeISO 格式化为ISO时间
func FormatTimeISO(t time.Time) string {
	return t.Format(time.RFC3339)
}

// ParseDuration 解析持续时间字符串
func ParseDuration(s string) (time.Duration, error) {
	return time.ParseDuration(s)
}

// Timestamp 获取当前时间戳
func Timestamp() int64 {
	return time.Now().Unix()
}

// TimestampMs 获取当前毫秒时间戳
func TimestampMs() int64 {
	return time.Now().UnixMilli()
}

// SleepWithContext 带上下文的睡眠
func SleepWithContext(ctx context.Context, d time.Duration) error {
	timer := time.NewTimer(d)
	defer timer.Stop()

	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-timer.C:
		return nil
	}
}
